package cn.wolfcode.trip.app.controller;


import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/sessions")
public class SessionController {

    @Autowired
    private IUserService userService;

    @PostMapping
    public Object login(String email,String password) {
        JSONResult result = new JSONResult();
        try {
            User user=userService.login(email,password);
            result.setObj(user);
            //把用户的信息存入到session中
            UserContext.setCurrentUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    @DeleteMapping
    public void logout(HttpSession session, HttpServletResponse response) {
        session.invalidate();
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
}
